/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.MDTOHtml;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.service.ArticleService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/14 17:19
 * 保存草稿的逻辑
 */
@Controller
public class SaveArticleController {
    CqLogger logger = CqLogger.getInstance();

    private final ArticleService articleService;

    public SaveArticleController(ArticleService articleService)
    {
        this.articleService = articleService;
    }

    @PostMapping("api/mdSave")
    public ResponseEntity<Map<String, Object>> SaveArticle(HttpServletRequest request, @RequestBody Map<String, String> requestMap){
        // 返回值
        Map<String, Object> resultMap = new HashMap<>();

        String articleTitle = requestMap.get("articleTitle");
        // md格式的内容
        String articleContentMd = requestMap.get("articleContentMd");
        // html格式的内容
        MDTOHtml mdtoHtml = MDTOHtml.getInstance(articleContentMd);
        String articleContentHtml = mdtoHtml.toHtml();
        try {
            articleService.saveArticle(articleTitle, articleContentHtml, articleContentMd, ResultCode.statusDraft);
            logger.print("数据库保存");
            resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
            resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
            return ResponseEntity.ok(resultMap);
        }catch (Exception e){
            logger.print(e);
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_UPLOAD_ERROR);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_UPLOAD_ERROR);
        }

        return ResponseEntity.ok(resultMap);
    }
}
